<template>
  <div class="news-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>汽车资讯</h1>
      <div class="news-filters">
        <div class="search-box">
          <input type="text" v-model="searchKeyword" placeholder="搜索资讯..." @keyup.enter="fetchNews">
          <button @click="fetchNews">搜索</button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">{{ error }}</div>

    <!-- 资讯列表 -->
    <div v-else class="news-list">
      <article class="news-item" v-for="item in newsItems" :key="item.id">
        <div class="news-image">
          <img :src="item.picUrl || '/src/images/demo1.jpg'" :alt="item.title">
        </div>
        <div class="news-content">
          <div class="news-meta">
            <span class="category">{{ item.category || '汽车资讯' }}</span>
            <span class="date">{{ formatDate(item.ctime || new Date().toISOString()) }}</span>
          </div>
          <h2 class="news-title">{{ item.title }}</h2>
          <p class="news-summary">{{ item.summary }}</p>
          <a :href="item.url" target="_blank" class="read-more">阅读全文 <i class="icon-arrow-right"></i></a>
        </div>
      </article>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="!loading && !error && totalPages > 1">
      <button 
        @click="currentPage = Math.max(1, currentPage - 1)"
        :disabled="currentPage === 1"
      >
        上一页
      </button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button 
        @click="currentPage = Math.min(totalPages, currentPage + 1)"
        :disabled="currentPage === totalPages"
      >
        下一页
      </button>
    </div>

    <!-- 无数据提示 -->
    <div v-if="!loading && !error && newsItems.length === 0" class="no-data">
      <p>没有找到相关资讯</p>
    </div>
  </div>
</template>
  
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import Qs from 'qs';

// 响应式状态
const newsItems = ref([]);
const loading = ref(false);
const error = ref(null);
const currentPage = ref(1);
const pageSize = ref(12);
const totalPages = ref(2);
const selectedCategory = ref('all');
const searchKeyword = ref('');

// 方法定义

const fetchNews = async () => {
  loading.value = true;
  error.value = null;

  try {
    const response = await axios({
      method: 'post',
      url: 'https://apis.tianapi.com/auto/index',
      data: Qs.stringify({
        key: '4f221d8165c79922259c371a2344b33b',
        num: pageSize.value,
        keyword: searchKeyword.value,
        type: selectedCategory.value === 'all' ? undefined : selectedCategory.value
      }),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    if (response.data.code === 200) {
      // 如果有关键词则进行本地模糊匹配
      let filteredItems = response.data.result.newslist;
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        filteredItems = filteredItems.filter(item => 
          (item.title && item.title.toLowerCase().includes(keyword)) ||
          (item.description && item.description.toLowerCase().includes(keyword)) ||
          (item.content && item.content.toLowerCase().includes(keyword))
        );
      }

      newsItems.value = filteredItems.slice(0, 24).map(item => ({
        ...item,
        title: item.title || '无标题',
        summary: item.description || item.content || '无摘要内容'
      }));
      totalPages.value = Math.min(2, Math.ceil(newsItems.value.length / pageSize.value));
    } else {
      throw new Error(response.data.msg);
    }
  } catch (err) {
    error.value = err.message || '获取资讯失败，请稍后重试';
    console.error('News API error:', err);
  } finally {
    loading.value = false;
  }
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchNews();
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchNews();
  }
};

const formatDate = (dateString) => {
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      return '日期未知';
    }
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  } catch {
    return '日期未知';
  }
};

// 模拟API响应数据


// 生命周期钩子
onMounted(() => {
  fetchNews();
});
</script>

<style scoped>
.news-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2rem;
  margin-bottom: 15px;
  color: #616161;
}

.news-filters {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.news-filters select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  height: 38px;
  line-height: 20px;
}

.search-box {
  display: flex;
  flex: 1;
  max-width: 400px;
  
}

.search-box input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-right: none;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
  height: 38px;
  box-sizing: border-box;
  line-height: 20px;
}

.search-box button {
  padding: 8px 12px;
  background-color: #47494b;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  height: 38px;
  box-sizing: border-box;
}

.loading-spinner {
  text-align: center;
  padding: 50px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #0066cc;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  background-color: #fff0f0;
  color: #e63946;
  padding: 15px;
  border-radius: 4px;
  text-align: center;
  margin: 20px 0;
}

.news-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.news-item {
  background-color: rgb(55, 55, 55);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  margin-bottom: 15px;
}

.news-item:hover {
  transform: translateY(-5px);
}

.news-image img {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.news-content {
  padding: 12px 15px;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #d0cece;
  margin-bottom: 8px;
}

.category {
  background-color: #f0f7ff;
  color: #2e3945;
  padding: 2px 8px;
  border-radius: 12px;
}

.news-title {
  font-size: 18px;
  margin-bottom: 10px;
  line-height: 1.3;
  max-height: 46.8px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.news-summary {
  color: #bdbdbd;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  max-height: 63px;
}

.read-more {
  display: inline-flex;
  align-items: center;
  color: #b6b6b6;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
}

.read-more i {
  margin-left: 5px;
  font-size: 12px;
}

.pagination {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #4a90e2;
  background: #4a90e2;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination button:hover:not(:disabled) {
  background: #3a7bc8;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #cccccc;
  border-color: #cccccc;
}

.no-data {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

@media (max-width: 768px) {
  .news-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    max-width: none;
  }

  .news-list {
    grid-template-columns: 1fr;
  }
}
</style>